package com.ycw.executor;

import lombok.Data;
import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * @author gonghl
 * @date 2019-09-10
 */
@Data
public class ZookeeperExecutor implements Watcher {
    private ZooKeeper zooKeeper;

    public ZookeeperExecutor(String hostPort) {
        try {
            zooKeeper = new ZooKeeper(hostPort, 30000, this);
            System.out.println("创建zookeeper成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String create(String path,String data) {
        try {
            return zooKeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void process(WatchedEvent event) {
        System.out.println(event);
        String path = event.getPath();
        if (path != null) {
            try {
                zooKeeper.exists(path, this);
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
